<?php
namespace app\index\controller;

use think\Request;
use think\Session;
use app\backend\model\Auth as AuthModel;
use GuzzleHttp\Client;

class Auth extends BaseController
{
    public function index()
    {
        $http = new Client;
        $response = $http->get('http://httpbin.org/get?a=aa&b=123');
        // $response = $http->post('http://httpbin.org/post?a=aa&b=123', ["aa" => 123, "bb" => "bb"]);
        // $response = $http->post('http://httpbin.org/post?a=aa&b=123', ["body" => '{"aa": 123, "bb": "bb"}']);
        // echo "<pre>";
        // print_r($response);
        // echo "</pre>";
        // 
        var_dump($response->getStatusCode());
        echo "<hr>";
        var_dump($response->getReasonPhrase());
        // echo "<hr>";
        // var_dump((string)$response->getBody());
    }

    public function auth()
    {
        // 渲染模板输出
        return $this->fetch('auth/auth');
    }

    /* 经典 OAuth2 */
    /*
    // 获取授权码
    public function oauth2()
    {
        // $request->session()->put('state', $state = Str::random(40));
        $state = "asdfghadfhasdfh";
        Session::set('state', $state);
        $query = http_build_query([
            // 必须是一个真实的 客户端ID。
            'client_id' => 4,//'client-id',
            'redirect_uri' => 'http://www.tp505.cm/index/auth/callback',
            'response_type' => 'code',
            'scope' => '',
            'state' => $state,
        ]);
        $this->redirect('http://www.laravel71202.cm/oauth/authorize?'.$query);
    }

    // 使用获取到的 授权码 得到访问令牌
    // http://www.tp505.cm/index.php?s=index/auth/callback&code=def5020084ab3cf4390fb263eca8a27ca99fe8cf3b6cc5dd842659a6506856a8092116e12a4e323734595412b2fffba0ed5b502a8742cd3aed63e75f7e57ca209cba90fa822e3363a9952f76c7d98a47ef9c28e61b569007a19b7979f523591f41d10718866c8509e2d3dcf0a8e17fcc809f5ce75d6d54838c75deac94f53408316ba59f5aa38c0ee2938c86f8037ffcb700031d2554e5b1d8b84d3156a89e96e806abd2a40b7921a26f3d849a4439045415c1e8c59335ffd4403ecdab97873cec7d2945e4bd113a79ae36e162c588cc44d8ad544cfad67a40b92acad763cbdb228982a5a0f458a815910c3d7354b2631d76bc24c102355cfdcc77e406b964c011c82ea8c9dc4bbdf7ef8923650a98e13cdab85d46075649f50ec9263decc32f3274752f597aa331a47b2bc26b95542b68c0e89266fe4a7d2237b7df191bd803aac5c23b0b7c4376ee2890c2f854220219207135c2fee080424871c0477a3fb9665e0a78b77a3c76fae40badd2dc495647ad0eea28&state=asdfghadfhasdfh
    public function callback(Request $request)
    {
        $code = $request->get('code');
        $sessionState = Session::get('state');
        $requestState = $request->get('state');

        if (empty($sessionState) || empty($requestState) || ($sessionState != $requestState)) {
            throw new Exception("Error Processing Request", 1);
        }

        $http = new Client;
        $response = $http->post('http://www.laravel71202.cm/oauth/token', [
            'form_params' => [
                'grant_type' => 'authorization_code',
                'client_id' => 4,//'client-id',
                'client_secret' => '2oEWENnu6i4r4wjsg9e0tw6TLtPGnCB0Qte42dL3',//'client-secret',
                // 这里的跳转地址，仅仅是判断用的，不会再进行跳转，但也是必须的，而且必须与上面的保持一致。
                'redirect_uri' => 'http://www.tp505.cm/index/auth/callback',
                'code' => $code
            ],
        ]);

        // access_token 等信息
        pre(json_decode((string) $response->getBody(), true));
    }

    public function doRequest1()
    {
        // Access-Token
        $http = new Client;
        $response = $http->get('http://www.laravel71202.cm/api/test001', [
            'headers' => [
                'Authorization' => 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiI0IiwianRpIjoiMDZkODAyMGZjM2FiN2Y5ZGYxN2Q5NTRlZGQ4ZWZjYzg4NzU5NzZlNjEwZjE1OWE1OGYyNDQxNTA1N2U1NjI5NDhlZTExMDc4YTYxNTQ1ZWIiLCJpYXQiOjE3NTM1OTE5NzAsIm5iZiI6MTc1MzU5MTk3MCwiZXhwIjoxNzU0ODg3OTY5LCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.RFnHC5lFrKN-Va_fqyqMcMFgLhr6EfwwYBJwknjBINZPxL196q34vO1_yKyvrrU-uE8nZiofpBPh9TgG8FRbg0WNEfDkz3Aj42vXhscOduX9XjlrbM38AmwQtSIsfG_3SNAvwOmtAfd29YLXl_ET7hSUKukynMu64pd06SsW8hLNIJOdV9I89WIsGEgP8TP1KefIrJ-TpT0FgKUAa_hoEf9Y5uNXzSqUaOCWj2j3uw3Wet9ZiBnkYUsYzbYpw5t2HkKFQRbdVvxW29028SYlADFSGKdxX9whDKx0TWpfkTjtex0SCSglkcgAW2pHb2XfQW-sTabh3xVlRAEGv8lPYhmvn-bBBMO6RC3BCZ-B5CdoITyLE7zWkd1yNsywShllBmHrxYeAKCi-wavFr6tIERp-WjG63Mkb8AK-uXOL28ZwsZUiXcXhjRs359LNDx6XHlLdmMgtPE5CDufMHrCgf1ZDa4PqJLHi6ARFKOz3HraveT0p6bqLC8tZFW1q1xFDqE7x1-kVGLoFvdewsg490jjJkcibgakQqfmKlhvrePWaYcUPfmwYfh2H_f5Pui_psV0FwRxrFRPhoxXpJizNQulL-TIVzfGGFgSOL9lBFkcnE2u99_h6VDwRzvED40Ts5Z-MmbNoFZ4zLbCujZBj9YVzpanLzudhwEWkN8wZ4ZE'
            ]
        ]);
        var_dump($response->getStatusCode());
        echo "<hr>";
        var_dump($response->getReasonPhrase());
        echo "<hr>";
        var_dump((string)$response->getBody());
    }

    */

    public function getSession()
    {
        var_dump(Session::get('state'));
    }

    /* PKCE授权令牌 */
    /*
    public function pkce()
    {
        $state = str_random(32);
        session('state', $state);

        $codeVerifier = str_random(100);
        session('code_verifier', $codeVerifier);

        $encoded = base64_encode(hash('sha256', $codeVerifier, true));
        $codeChallenge = strtr(rtrim($encoded, '='), '+/', '-_');

        $query = http_build_query([
            'client_id' => '3',
            'redirect_uri' => 'http://www.tp505.cm/index/auth/callback',
            'response_type' => 'code',
            'scope' => '',
            'state' => $state,
            'code_challenge' => $codeChallenge,
            'code_challenge_method' => 'S256',
        ]);

        $this->redirect('http://www.laravel71202.cm/oauth/authorize?'.$query);
    }

    public function callback(Request $request)
    {
        $code = $request->get('code');
        $sessionState = Session::get('state');
        $requestState = $request->get('state');
        $codeVerifier = session('code_verifier');
        if (empty($sessionState) || empty($requestState) || ($sessionState != $requestState)) {
            throw new Exception("Error Processing Request", 1);
        }

        $encoded = base64_encode(hash('sha256', $codeVerifier, true));
        $codeChallenge = strtr(rtrim($encoded, '='), '+/', '-_');

        $http = new Client;
        $response = $http->post('http://www.laravel71202.cm/oauth/token', [
            'form_params' => [
                'grant_type' => 'authorization_code',
                'client_id' => 3,//'client-id',
                'redirect_uri' => 'http://www.tp505.cm/index/auth/callback',
                'code_verifier' => $codeVerifier,
                'code' => $code
            ],
        ]);

        // access_token 等信息
        pre(json_decode((string) $response->getBody(), true));
    }
    */

    /* 密码授权令牌 */
    /*public function passwordToken(Request $request)
    {
        $http = new Client;
        $response = $http->post('http://www.laravel71202.cm/oauth/token', [
            'form_params' => [
                'grant_type' => 'password',
                'client_id' => '2',
                'client_secret' => 'uoQetAwkc1Np3KKBJqJK5FAWFxkIvv8ZD903Db6s',
                'username' => 'auv@qq.com',
                'password' => '1qaz#EDC',
                'scope' => '',
            ]
        ]);

        // access_token 等信息
        pre(json_decode((string) $response->getBody(), true));
    }*/

    /* 隐式授权令牌 */
    public function implicitToken()
    {
        $state = str_random(32);
        session('state', $state);

        $query = http_build_query([
            'client_id' => 1,
            'redirect_uri' => 'http://www.tp505.cm/index/auth/callback',
            'response_type' => 'token',
            'scope' => '',
            'state' => $state,
        ]);

        $this->redirect('http://www.laravel71202.cm/oauth/authorize?'.$query);
    }

    // http://www.tp505.cm/index/auth/callback#access_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiYWYyYTJiZmY0ZWU1NWY3ZDFmMTU1NGNjNjVhNTYzNzIyY2MyMGJkMGNiZTlmNjJjNzQ1Yzk5YTE2MmNiOTE0N2U1NDlkNTg1YmMxOGZlYmQiLCJpYXQiOjE3NTM1OTYwMTEsIm5iZiI6MTc1MzU5NjAxMSwiZXhwIjoxNzU0ODkyMDExLCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.JxJRPEdnKQom9rz7mvfmCJ0p-DKmVX4nMaTOnXRJ5yy8l9D2uEp5QN0AKGradQmWUCvHGpt5UbmdHsGPI_4TKXKShUcG2IC_UB3rwZ5P1YdiCNMfsgOiSVovhrKGcuXC-85iphcPSiaGDP22Ipod1dH5QSyqLe0_Asq8btAF8RiXFDJqtxUj_8KoIs1Rs9s94dXCr8nCIFgHm8ignWmA8QhLgCOv-FZMIWt4H0FQ8t8Q0hqQYxM_5uyOyv0VMmsNnGFttpcB2wJUR476ER2cZU248z6dm7BNbyiMgq1V0ydXpJ69dM44kNNpLLDM1M2TfyYT_sVt8lLa2JtE7N7AWTFI-gijpVMGjuI6gKQoqbRcU9OO4whleKCHMjTVo4wTfhqPG-AF9Po_q0UE6xXPQP6QJt50JaFZrdw5p4z4vHJ5R8Lc9XRIa6PZgXxh_Qe-fBPBB8iJ_ZZxWuc2O1BSR6kjkW4BUAIce5Q3mjm9x-Wpt6FCOjEjb1Kc6i3ueAsq7xViuBRc1CzFIBoFqKdgslrmUAcAOL-IasRd6KU4M5eHWK7jTHi1fQ42moWSGwAIqpz7VMfiMnZsghsH5i3ygyVzZol3BDf8x2WNdR5qTLyZ-Cr1SPj0aahN8V3ra6pRVIax9vOspbAWL21Uul3-SP7prZFORziAVdMeR1_EOkE&token_type=Bearer&expires_in=1296000&state=yxxu0Mu7E5BV3HdWxZ3nVqCstpiF49WK
    public function callback(Request $request)
    {
        // php 服务器无法获取 # 锚点数据
        // 只能使用js 了。
        return $this->fetch('implicitToken');
    }
}

